package com.renovate.portal.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import android.util.Log;

public class Helpers {

	private static Helpers instance;

	public static String buildprop_path() {
		if (new File("/system/build.prop").exists()) {
			return "/system/build.prop";
		} else {
			return null;
		}

	}

	public static Helpers getInstance() {
		if (instance == null)
			return new Helpers();
		else
			return instance;
	}

	/**
	 * Get mounts
	 * 
	 * @param mount
	 * @return success or failure
	 */
	public static boolean getMount(final String mount) {
		final CMDProcessor cmd = new CMDProcessor();
		final String mounts[] = getMounts("/system");
		if (mounts != null && mounts.length >= 3) {
			final String device = mounts[0];
			final String path = mounts[1];
			final String point = mounts[2];
			if (cmd.su.runWaitFor(
					"mount -o " + mount + ",remount -t " + point + " " + device
							+ " " + path).success()) {
				return true;
			}
		}
		return (cmd.su.runWaitFor("busybox mount -o remount," + mount
				+ " /system").success());
	}

	/**
	 * Return mount points
	 * 
	 * @param path
	 * @return line if present
	 */
	public static String[] getMounts(final String path) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(
					"/proc/mounts"), 256);
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.contains(path)) {
					return line.split(" ");
				}
			}
			br.close();
		} catch (FileNotFoundException e) {
			Log.d("Renovate", "/proc/mounts does not exist");
		} catch (IOException e) {
			Log.d("Renovate", "Error reading /proc/mounts");
		}
		return null;
	}

	public static String getProp(String prop) {
		try {
			Process process = Runtime.getRuntime().exec("getprop " + prop);
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(process.getInputStream()));
			StringBuilder log = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				log.append(line);
			}
			return log.toString();
		} catch (IOException e) {
			// Runtime error
		}
		return null;
	}

	public static String getROMVersion() {
		Helpers.getInstance();
		String romVersion = Helpers.getProp("ro.rom.id");
		if (romVersion != null)
			return romVersion;
		else
			return "<none>";
	}
	
	public static String getDevice() {
		Helpers.getInstance();
		String romVersion = Helpers.getProp("ro.product.device");
		if (romVersion != null)
			return romVersion;
		else
			return "<none>";
	}

	// Check to see if Renovate ROM is installed

	/**
	 * Read file via shell
	 * 
	 * @param filePath
	 * @param useSu
	 * @return file output
	 */
	public static String readFileViaShell(String filePath, boolean useSu) {
		CMDProcessor.CommandResult cr = null;
		if (useSu) {
			cr = new CMDProcessor().su.runWaitFor("cat " + filePath);
		} else {
			cr = new CMDProcessor().sh.runWaitFor("cat " + filePath);
		}
		if (cr.success())
			return cr.stdout;
		return null;
	}

	public static String readOneLine(String fname) {
		String line = null;
		if (new File(fname).exists()) {
			BufferedReader br;
			try {
				br = new BufferedReader(new FileReader(fname), 512);
				try {
					line = br.readLine();
				} finally {
					br.close();
				}
			} catch (Exception e) {
				// Log.e("Renovate", "IO Exception when reading sys file", e);
				// attempt to do magic!
				return readFileViaShell(fname, true);
			}
		}
		return line;
	}

	/**
	 * Write one line to a file
	 * 
	 * @param fname
	 * @param value
	 * @return if line was written
	 */
	public static boolean writeOneLine(String fname, String value) {
		if (!new File(fname).exists()) {
			return false;
		}
		try {
			FileWriter fw = new FileWriter(fname);
			try {
				fw.write(value);
			} finally {
				fw.close();
			}
		} catch (IOException e) {
			String Error = "Error writing to " + fname + ". Exception: ";
			Log.e("Renovate", Error, e);
			return false;
		}
		return true;
	}

	HashMap<String, String> props;

	public Helpers() {
		readBuildProp();
	}

	private void readBuildProp() {
		props = new HashMap<String, String>();
		try {
			FileInputStream fstream = new FileInputStream("/system/build.prop");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				// System.out.println(strLine);
				String[] line = strLine.split("=");
				if (line.length > 1)
					props.put(line[0], line[1]);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
